package com.leo.blog.service.impl;

import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.leo.blog.annotatiton.SystemLog;
import com.leo.blog.dao.PingDao;
import com.leo.blog.dto.PingExecution;
import com.leo.blog.entity.Ping;
import com.leo.blog.enums.PingStateEnum;
import com.leo.blog.exceptions.PingOperationException;
import com.leo.blog.service.PingService;
import com.leo.blog.util.ConstantUtil;
import com.leo.blog.util.PageCalculator;

@Service
public class PingServiceImpl implements PingService{
	@Autowired
	private PingDao pingDao;

	@Override
	@SystemLog(description = ConstantUtil.PING_ADD, userType = ConstantUtil.USERTYPE_USER)
	public PingExecution addPing(String name, Ping ping) throws PingOperationException {
		if(ping != null) {
			//初始化创建时间
			ping.setCreateTime(new Date());
			
			int effectedNum = pingDao.insertPing(ping);
			if(effectedNum > 0) {
				return new PingExecution(PingStateEnum.SUCCESS);
			}else {
				return new PingExecution(PingStateEnum.OFFLINE);//-1
			}
		}else {
			return new PingExecution(PingStateEnum.NULL_PING);
		}
	}

	@Override
	@SystemLog(description = ConstantUtil.PING_DELETE, userType = ConstantUtil.USERTYPE_ADMIN)
	public PingExecution deletePingByPingId(String name, int pingId) {
		int effectedNum = pingDao.deletePingByPingId(pingId);
		if(effectedNum > 0) {
			return new PingExecution(PingStateEnum.SUCCESS);
		}else {
			return new PingExecution(PingStateEnum.OFFLINE);//-1
		}
	}

	@Override
	public PingExecution getPingListByBlogId(Ping pingCondition, int pageIndex, int pageSize) {
		PingExecution pe = new PingExecution();
		//将页码转换成行码
		int rowIndex = PageCalculator.calculateRowIndex(pageIndex, pageSize);
		//根据查询条件,待用dao层返回相关类型列表
		List<Ping> pingList = pingDao.queryPingListByBlogId(pingCondition, rowIndex, pageSize);
		int count = pingDao.queryPingListByBlogIdCount(pingCondition);
		if(pingList != null && count > 0) {
			pe.setPingList(pingList);
			pe.setCount(count);
			pe.setState(PingStateEnum.SUCCESS.getState());
		}else {
			pe.setState(PingStateEnum.OFFLINE.getState());
		}		
		return pe;
	}

}
